package cn.cherish.controller;

import cn.cherish.domain.User;
import cn.cherish.feign.OrderFeign;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


//订单服务
@RestController
//@DefaultProperties(defaultFallback = "fallbackMethod") //统一默认配置
public class OrderController {

    //需要配置成Bean
    @Autowired
    private RestTemplate restTemplate ;
    @Autowired
    private DiscoveryClient discoveryClient;
//    @Autowired
//    OrderFeign orderFeign;

    //浏览器调用该方法


    @HystrixCommand(fallbackMethod = "fallbackMethod")   //方法熔断
    @GetMapping(value = "/findById/{id}")
    public User getById(@PathVariable("id")Long id){
        //发送http请求调用 user的服务，获取user对象 ： RestTemplate
        //目标资源路径：user的ip,user的端口，user的Controller路径
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-server");
//        if (instances == null || instances.size()<= 0){
//            return null;
//        }
//        ServiceInstance serviceInstance = instances.get(0);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//        System.out.println(host);
//        System.out.println(port);
//        String url = "http://"+host+":"+port+"/user/"+id;

        // ribbon
        String url = "http://user-server/findById/"+id;

        //模拟业务逻辑比较繁忙，执行降级方法
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        //发送http请求
        return restTemplate.getForObject(url, User.class);

        //openFeign
//        User user = orderFeign.getById(id);
//        return user;

    }

    public User fallbackMethod(@PathVariable("id")Long id){
        //返回托底数据
        return new User(-1L ,"无此用户","用户服务不可用");
    }
}